<template>
  <div v-loading="loading">
    <el-form ref="formRef" :model="infoForm" :rules="rules" label-width="120px">
      <el-scrollbar ref="scrollbarRef" height="600px">
        <el-form-item label="应用图标:" prop="icon">
          <el-row style="width: 100%">
            <el-col :span="24">
              <ImageUpload :count="1" :fileHandle="handleIconFiles" :file-list="iconUserFile" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-text class="mx-1" type="info" size="small">应用显示图标</el-text>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="一句话介绍:" prop="shortDesc">
          <el-input v-model="infoForm.shortDesc" />
        </el-form-item>
        <el-form-item label="详细介绍:" prop="desc">
          <el-input v-model="infoForm.desc" type="textarea" />
        </el-form-item>
        <el-form-item label="隐私政策网址:" prop="privacyUrl">
          <el-input v-model="infoForm.privacyUrl" />
        </el-form-item>
        <el-form-item label="ICP备案号:" prop="icp">
          <el-input v-model="infoForm.icp" />
        </el-form-item>
        <el-form-item label="应用截图:" prop="screenshot">
          <ImageUpload :count="5" :fileHandle="handleScreenshotFiles" :file-list="screenshotFile" />
        </el-form-item>
        <el-form-item label="安全评估报告:" prop="safetyReport">
          <FileUpload
            :count="10"
            :file-handle="handleSafetyReportFiles"
            :file-list="safetyReportFile"
            list-type="text"
          />
        </el-form-item>
      </el-scrollbar>
      <!-- <el-divider>发布平台</el-divider>
      <el-form-item label-width="0" prop="plates">
        <el-checkbox-group v-model="infoForm.plates">
          <el-checkbox v-for="plat in plats" :key="plat" :label="plat">{{ plat }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item> -->
      <el-divider />
      <el-row>
        <el-col :span="12">
          <el-button @click="closeInfo">取消</el-button>
          <el-button type="primary" @click="onSubmit(formRef)">保存</el-button>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-button type="primary" @click="onSync">同步在线资料</el-button>
          <el-button type="success" disabled>提交在线审核</el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, inject, onBeforeMount } from 'vue'
import ImageUpload from '@/components/ImageUpload.vue'
import FileUpload from '@/components/FileUpload.vue'
import type { FormInstance, FormRules, UploadFiles, UploadUserFile } from 'element-plus'
import type { AppInfoType } from '../api/types'
import { EditAppInfoApi, GetAppInfoApi, AppSyncApi } from '../api'
import { useCounterStore } from '../stores/manage'

const loading = ref(false)

// 全局状态管理器
const manager = useCounterStore()

// 表单实例
const formRef = ref<FormInstance>()
// 图标
const iconUserFile = ref<UploadUserFile[]>([])
// 应用截图
const screenshotFile = ref<UploadUserFile[]>([])
// 安全报告
const safetyReportFile = ref<UploadUserFile[]>([])

const plats = ref([])

onBeforeMount(async () => {
  // 获取应用详情
  getInfo()
})

const getInfo = () => {
  GetAppInfoApi(manager.getAppId())
    .then((response) => {
      const result = response.data
      if (result.code == 200) {
        if (result.data != null) {
          infoForm.value = result.data
          if (result.data.icon != '') {
            // 图标
            iconUserFile.value = [
              {
                name: 'icon',
                url: result.data.icon
              }
            ]
            // 截图
            const screenshots = result.data.screenshot
            var screenshotUserFile: UploadUserFile[] = []
            if (screenshots != null) {
              for (let i = 0; i < screenshots.length; i++) {
                screenshotUserFile[i] = {
                  name: 'screenshot',
                  url: screenshots[i]
                }
              }
              screenshotFile.value = screenshotUserFile
            }
          }
          plats.value = result.data.plats
        }
      }
    })
    .catch((error) => {
      console.log(error)
    })
}

// 图标文件变化后的回调
const handleIconFiles = (files: UploadFiles) => {
  iconUserFile.value = files
  infoForm.value.icon = files
}

// 截图文件变化后的回调
const handleScreenshotFiles = (files: UploadFiles) => {
  console.log(files)
  screenshotFile.value = files
}

// 安全报告文件回调
const handleSafetyReportFiles = (files: UploadFiles) => {
  safetyReportFile.value = files
  infoForm.value.safetyReport = files
}

// 校验规则
const rules = reactive<FormRules<AppInfoType>>({
  icon: [{ required: true, message: '请选择应用图标', trigger: 'blur' }],
  shortDesc: [{ required: true, message: '一句话介绍不能为空', trigger: 'blur' }],
  desc: [{ required: true, message: '介绍不能为空', trigger: 'blur' }],
  privacyUrl: [{ required: true, message: '隐私政策不能为空', trigger: 'blur' }],
  // icp: [{ required: true, message: 'ICP备案号不能为空', trigger: 'blur' }],
  screenshot: [{ required: true, message: '应用截图不能为空', trigger: 'change' }],
  // safetyReport: [{ required: true, message: '安全报告不能为空', trigger: 'change' }],
  plates: [{ required: true, message: '请选择发布的应用平台', trigger: 'blur' }]
})

// 绑定模型
const infoForm = ref<AppInfoType>({
  icon: '',
  shortDesc: '',
  desc: '',
  privacyUrl: '',
  icp: '',
  safetyReport: '',
  plates: [],
  screenshot: []
})

// 保存资料
const onSubmit = async (formEl: FormInstance | undefined) => {
  // 非空判断
  if (!formEl) return
  // 数据校验
  await formEl.validate((valid, fields) => {
    if (valid) {
      EditAppInfoApi(infoForm.value)
        .then((response) => {
          console.log(response)
        })
        .catch((error) => {
          console.log(error)
        })
    }
  })
}

const onSync = () => {
  loading.value = true
  AppSyncApi(manager.getAppId())
    .then((res) => {
      if (res.data.code == 200) {
        getInfo()
      }
    })
    .catch((error) => {
      console.log(error)
      
    }).finally(() => {
      loading.value = false
    })
}

// 父级页面的关闭函数
const closeInfo: Function = inject('closeInfo') as Function
</script>
